﻿using System.Configuration;

namespace System.Web.Mvc   //这里只能引用mvc的空间
{
    public static class MyUrlHelper
    {
        public static string Scrpit(this UrlHelper helper, string value)
        {
            string jsCssVersion = ConfigurationManager.AppSettings["Version"];
            if (string.IsNullOrEmpty(jsCssVersion))
            {
                return helper.Content(value); 
            }
            else
            {
                return helper.Content(string.Format(value + "?_v={0}", jsCssVersion));
            }

        }
        /**/
        /// <summary>
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址
        /// </summary>
        public static string GetIPAddress(System.Web.HttpContext context)
        {
            string result = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理
                if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];    //找到不是内网的地址
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式 ,IsIPAddress判断是否是IP的方法,
                        return result;
                    else
                        result = null;    //代理中的内容 非IP，取IP
                }

            }
            result = (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : context.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
                result = context.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = context.Request.UserHostAddress;
            return result;
        }
        #region bool IsIPAddress(str1) 判断是否是IP格式
        /**/
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regformat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        /// <summary>
        /// 获取请求客户端的Ip地址,无视代理服务器
        /// </summary>
        /// <returns></returns>
        public static string GetIp()
        {
            string customerIP = "127.0.0.1";
            try
            {
                if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null && System.Web.HttpContext.Current.Request.ServerVariables != null)
                {
                    customerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                    if (string.IsNullOrEmpty(customerIP)) //获取不到
                    { 
                        customerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0].Trim();;
                        if (String.IsNullOrEmpty(customerIP))
                        { 
                            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                            {
                                customerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"];
                                if (customerIP == null)
                                    customerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                            }
                            else if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                            {
                                customerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                            }
                            else 
                                customerIP = System.Web.HttpContext.Current.Request.UserHostAddress;
                        }
                    }
                }
                if(!IsIPAddress(customerIP)) //验证格式
                    customerIP = "127.0.0.1";
            }
            catch
            {
                //todo
            }
            return customerIP;
        }
        #endregion
    }
}